<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<head>
	<script type="text/javascript">
		var sour=[];
		var goal = 0;
		var exhaustion=[];

		function computeExe() {
			sour=[];
			goal = 0;
			if(init()){
				compute();
			}
		}
		function computeIsLessGloa(tmp){
			var sum =0;
			for(var i = 0; i <= tmp.length; i++){
				sum = sum+parseInt(tmpin[k])
			}
		}

		function compute(){
			exhaustion=[];
			for (var a2 = []; a2.push([]) < sour.length;);
			var le = Math.pow(2, sour.length)-1;
			for (var i = 1; i <= le; i++) {
				var t = [];
				for (var s=i,k=0; s>0; s>>=1,k++){
					if (s&1==1){
						t.push(sour[k]);
					}
				}
				a2[t.length-1].push(t);
			}
			exhaustion=a2;

			while(true){
				if(loopSum()){
					return;
				}
				goal+=1;
			}
			exhaustion=[];
		}

		function init() {
			outMessage("");
			var pageSum = 0;
			var readPageAmount = document.getElementById('sour').value;
			readPageAmount=readPageAmount.replace(/，/g,",");
			var amountArr = readPageAmount.split(",");
			if(!readPageAmount.trim()){
				outMessage("输入每张金额!");
				return false;
			}
			sour = [];
			for (var i = 0; i < amountArr.length; i++) {
				sour[i] = parseInt(amountArr[i].trim());
				pageSum += sour[i];
			}

			var readAmount = document.getElementById('goal').value;
			if(!readAmount.trim()){
				outMessage("输入总金额");
				return false;
			}
			goal = parseInt(readAmount);
			if(!goal){
				outMessage("检查总金额格式!");
				return false;
			}
			if (goal > pageSum) {
				outMessage("输入发票累计金额不足!  还差："+(goal - pageSum));
				return false;
			}
			return true;
		}

		/**
		 * 循环相加
		 */
		function loopSum() {
			var goalArrTmp =[];

			for (var i = 0; i < exhaustion.length; i++) {
				var tmp = exhaustion[i];
				for(var j = 0;j<tmp.length;j++){
					var sum = 0;
					var tmpin = tmp[j];
					for(var k = 0;k<tmpin.length;k++){
						sum = sum+parseInt(tmpin[k])
					}

					if(goal == sum){
						outPrint(tmpin)
						return true;
					}
				}

			}
			return false;
		}


		/**
		 * 打印输出
		 *
		 * @param x
		 * @param tmp
		 */
		function outPrint(tmp) {
			var count = 0;
			var str="";
			var readAmount = document.getElementById('goal').value;
			var goalTmp = parseInt(readAmount);
			for (var i=0;i<tmp.length;i++) {
				if (tmp[i] > 0) {
					str= str+tmp[i]+",";
					count++;
				}
			}
			outMessage(str+" 最接近金额 :" + goal+" 张数 :" + count)
		}

		/**
		 * 输出内容
		 */
		function outMessage(obj){
			document.getElementById('message').innerText=obj;
		}
	</script>
</head>

<BODY>
<div>
	<span>输入总金额：</span>
	<br>
	<input name="goal" id="goal" type="text">
</div>
<div>
	<span>输入每张金额（“,隔开” 如 100,50,200）：</span>
	<br>
	<textarea name="sour" style="height: 100px;width: 500px;"id="sour"> </textarea>
</div>

<div>
	<span style="color: red;" id="message"></span>
</div>
<div>
	<input name="compute" id="compute" onclick="computeExe()" type="button" value="开始计算">
</div>
</BODY>
</HTML>
